package com.ivncorp.evnproject;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import com.ivncorp.evnproject.data.DaoMaster;
import com.ivncorp.evnproject.data.DaoMaster.DevOpenHelper;
import com.ivncorp.evnproject.data.DaoSession;
import com.ivncorp.evnproject.data.TramDao;
import com.ivncorp.evnproject.helpers.ExifHelpers;
import com.ivncorp.evnproject.helpers.LocationTracker;
import com.ivncorp.evnproject.helpers.SetupPhotos;
import com.ivncorp.evnproject.helpers.Utils;
import com.ivncorp.evnproject.helpers.Variables;
import com.ivncorp.evnproject.model.ObjectTram;

public class ActivityCreateTram extends Activity {

	private LocationTracker locationTracker;
	private static final int CAMERA_REQUEST_1 = 1;
	private static final int CAMERA_REQUEST_2 = 2;
	private static final int CAMERA_REQUEST_3 = 3;
	private static final int CAMERA_REQUEST_4 = 4;
	private static final int CAMERA_REQUEST_5 = 5;

	private Boolean Creat = true;

	private ObjectTram object;

	private String mCurrentPhotoPath = "";
	private HashMap<String, String> list_mCurrentPhotoPath;
	private SetupPhotos setupphotos;
	private ImageView ivGPS;
	private ImageView ivTruoc;
	private ImageView ivTrai;
	private ImageView ivPhai;
	private ImageView ivSau;
	private EditText txtCode;
	private EditText txtName;
	private EditText txtCapacity;
	private Bitmap bitmap = null;
	// for DAO
	private SQLiteDatabase dbDao;
	private DaoSession daoSession;
	private DaoMaster daoMaster;
	private TramDao tramDao;

	@SuppressLint("SimpleDateFormat")
	SimpleDateFormat dateFormat = new SimpleDateFormat(
			"yyyy-MM-dd hh:mm:ss.SSS");

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_create_tram);

		ivGPS = (ImageView) findViewById(R.id.ivAnhGPS);
		ivTruoc = (ImageView) findViewById(R.id.ivAnhTruoc);
		ivTrai = (ImageView) findViewById(R.id.ivAnhTrai);
		ivPhai = (ImageView) findViewById(R.id.ivAnhPhai);
		ivSau = (ImageView) findViewById(R.id.ivAnhSau);
		txtCode = (EditText) findViewById(R.id.txtTakePictureCode);
		txtName = (EditText) findViewById(R.id.txtTakePictureName);
		txtCapacity = (EditText) findViewById(R.id.txtTakePictureCapacity);

		locationTracker = new LocationTracker(this);
		// gpsTracker = new GPSTracker(this);
		list_mCurrentPhotoPath = new HashMap<String, String>();
		setupphotos = new SetupPhotos();

		// Dao
		DevOpenHelper helper = new DaoMaster.DevOpenHelper(
				getApplicationContext(), Variables.NAME_DATABSE, null);
		dbDao = helper.getWritableDatabase();
		daoMaster = new DaoMaster(dbDao);
		daoSession = daoMaster.newSession();
		tramDao = daoSession.getTramDao();
		Intent intent = getIntent();
		object = (ObjectTram) intent.getSerializableExtra("object");
		if (object != null) {

			txtCode.setText(object.getCode());
			txtName.setText(object.getName());
			txtCapacity.setText(String.valueOf(object.getCapacity()));

			final int width = ivTruoc.getLayoutParams().width;
			final int height = ivTruoc.getLayoutParams().height;

			String uri1 = object.getImage_1();
			if (uri1 != null) {
				bitmap = Utils.decodeFile(uri1, width, height);
				ivGPS.setImageBitmap(bitmap);
			}

			String uri2 = object.getImage_2();
			if (uri2 != null) {
				bitmap = Utils.decodeFile(uri2, width, height);
				ivTruoc.setImageBitmap(bitmap);
			}

			String uri3 = object.getImage_3();
			if (uri3 != null) {
				bitmap = Utils.decodeFile(uri3, width, height);
				ivTrai.setImageBitmap(bitmap);
			}

			String uri4 = object.getImage_4();
			if (uri4 != null) {
				bitmap = Utils.decodeFile(uri4, width, height);
				ivPhai.setImageBitmap(bitmap);
			}

			String uri5 = object.getImage_5();
			if (uri5 != null) {
				bitmap = Utils.decodeFile(uri5, width, height);
				ivSau.setImageBitmap(bitmap);
			}

			Creat = false;
		}
		getActionBar().setDisplayShowHomeEnabled(true);
		getActionBar().setDisplayHomeAsUpEnabled(true);
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
	}

	@Override
	protected void onDestroy() {
		if (bitmap != null) {
			bitmap.recycle();
			bitmap = null;
		}
		ivPhai.setImageBitmap(null);
		ivSau.setImageBitmap(null);
		ivTrai.setImageBitmap(null);
		ivTruoc.setImageBitmap(null);
		ivGPS.setImageBitmap(null);
		super.onDestroy();
	}

	public void imageclick(View view) {
		switch (view.getId()) {
		case R.id.layout1:
			Toast.makeText(this, R.string.hinh_truoc, Toast.LENGTH_LONG).show();
			dispatchTakePictureIntent(true, CAMERA_REQUEST_1);
			break;
		case R.id.layout2:
			Toast.makeText(this, R.string.anh_truoc, Toast.LENGTH_LONG).show();
			dispatchTakePictureIntent(false, CAMERA_REQUEST_2);
			break;
		case R.id.layout3:
			Toast.makeText(this, R.string.anh_trai, Toast.LENGTH_LONG).show();
			dispatchTakePictureIntent(false, CAMERA_REQUEST_3);
			break;
		case R.id.layout4:
			Toast.makeText(this, R.string.anh_phai, Toast.LENGTH_LONG).show();
			dispatchTakePictureIntent(false, CAMERA_REQUEST_4);
			break;
		case R.id.layout5:
			Toast.makeText(this, R.string.anh_sau, Toast.LENGTH_LONG).show();
			dispatchTakePictureIntent(false, CAMERA_REQUEST_5);
			break;
		default:
			break;
		}
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {

		if (resultCode == Activity.RESULT_OK) {
			if (mCurrentPhotoPath != null) {
				switch (requestCode) {
				case CAMERA_REQUEST_1:
					new ExifHelpers().setExifGPS(mCurrentPhotoPath,
							getApplicationContext());
					bitmap = Utils.decodeFile(mCurrentPhotoPath,
							ivGPS.getWidth(), ivGPS.getHeight());
					ivGPS.setImageBitmap(bitmap);
					list_mCurrentPhotoPath.put("1", mCurrentPhotoPath);
					break;
				case CAMERA_REQUEST_2:
					bitmap = Utils.decodeFile(mCurrentPhotoPath,
							ivTruoc.getWidth(), ivTruoc.getHeight());
					ivTruoc.setImageBitmap(bitmap);
					list_mCurrentPhotoPath.put("2", mCurrentPhotoPath);
					break;
				case CAMERA_REQUEST_3:
					bitmap = Utils.decodeFile(mCurrentPhotoPath,
							ivTrai.getWidth(), ivTrai.getHeight());
					ivTrai.setImageBitmap(bitmap);
					list_mCurrentPhotoPath.put("3", mCurrentPhotoPath);
					break;
				case CAMERA_REQUEST_4:
					bitmap = Utils.decodeFile(mCurrentPhotoPath,
							ivPhai.getWidth(), ivPhai.getHeight());
					ivPhai.setImageBitmap(bitmap);
					list_mCurrentPhotoPath.put("4", mCurrentPhotoPath);
					break;
				case CAMERA_REQUEST_5:
					bitmap = Utils.decodeFile(mCurrentPhotoPath,
							ivSau.getWidth(), ivSau.getHeight());
					ivSau.setImageBitmap(bitmap);
					list_mCurrentPhotoPath.put("5", mCurrentPhotoPath);
					break;
				default:
					break;
				}

				mCurrentPhotoPath = null;
			}

		} else {
			new File(mCurrentPhotoPath).delete();
		}

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// TODO Auto-generated method stub
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.activity_takepicture_action, menu);
		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// TODO Auto-generated method stub
		switch (item.getItemId()) {
		case R.id.action_takepicture:
			savedata();
			break;

		case android.R.id.home:
			finish();
			break;

		default:
			break;
		}

		return super.onOptionsItemSelected(item);
	}

	public void savedata() {

		String code = txtCode.getText().toString();
		String name = txtName.getText().toString();
		String capacity = txtCapacity.getText().toString();

		if (code.isEmpty()) {
			Toast.makeText(getApplicationContext(),
					R.string.yeu_cau_nhap_vao_ma_tram_, Toast.LENGTH_SHORT)
					.show();
			return;
		}
		if (name.isEmpty()) {
			Toast.makeText(getApplicationContext(),
					R.string.yeu_cau_nhap_vao_ten_tram_, Toast.LENGTH_SHORT)
					.show();
			return;
		}
		if (capacity.isEmpty()) {
			Toast.makeText(getApplicationContext(),
					R.string.yeu_cau_nhap_vao_cong_suat_, Toast.LENGTH_SHORT)
					.show();
			return;
		}

		ObjectTram ob = new ObjectTram();
		if (list_mCurrentPhotoPath.get("1") == null) {
			if (Creat) {
				Toast.makeText(getApplicationContext(),
						R.string.yeu_cau_anh_hinh_dang_, Toast.LENGTH_SHORT)
						.show();
				return;
			} else
				ob.setImage_1(object.getImage_1());
		} else {
			ob.setImage_1(list_mCurrentPhotoPath.get("1"));
		}
		if (list_mCurrentPhotoPath.get("2") == null) {
			if (Creat) {
				Toast.makeText(getApplicationContext(),
						R.string.yeu_cau_anh_truoc_, Toast.LENGTH_SHORT).show();
				return;
			} else
				ob.setImage_2(object.getImage_2());
		} else {
			ob.setImage_2(list_mCurrentPhotoPath.get("2"));
		}
		if (list_mCurrentPhotoPath.get("3") == null) {
			if (Creat) {
				Toast.makeText(getApplicationContext(),
						R.string.yeu_cau_anh_trai_, Toast.LENGTH_SHORT).show();
				return;
			} else
				ob.setImage_3(object.getImage_3());
		} else {
			ob.setImage_3(list_mCurrentPhotoPath.get("3"));
		}
		if (list_mCurrentPhotoPath.get("4") == null) {
			if (Creat) {
				Toast.makeText(getApplicationContext(),
						R.string.yeu_cau_anh_phai_, Toast.LENGTH_SHORT).show();
				return;
			} else
				ob.setImage_4(object.getImage_3());
		} else {
			ob.setImage_4(list_mCurrentPhotoPath.get("4"));
		}
		if (list_mCurrentPhotoPath.get("5") == null) {
			if (Creat) {
				Toast.makeText(getApplicationContext(),
						R.string.yeu_cau_anh_sau_, Toast.LENGTH_SHORT).show();
				return;
			} else
				ob.setImage_5(object.getImage_5());
		} else {
			ob.setImage_5(list_mCurrentPhotoPath.get("5"));
		}

		// test
		// ob.setImage_5("/mnt/sdcard/DCIM/Camera/bieu do luong du lieu muc dinh.jpg");
		// ob.setImage_4("/mnt/sdcard/DCIM/Camera/bieu do luong du lieu muc dinh.jpg");
		// ob.setImage_3("/mnt/sdcard/DCIM/Camera/bieu do luong du lieu muc dinh.jpg");
		// ob.setImage_2("/mnt/sdcard/DCIM/Camera/bieu do luong du lieu muc dinh.jpg");
		// ob.setImage_1("/mnt/sdcard/DCIM/Camera/bieu do luong du lieu muc dinh.jpg");

		ob.setUploaded((byte) 0);
		ob.setCode(code);
		ob.setName(name);
		ob.setCapacity(Integer.parseInt(capacity));
		Calendar calendar = Calendar.getInstance();
		Date date = new Date(calendar.getTimeInMillis());
		ob.setTimestamp(dateFormat.format(date));
		if (Creat) {
			try {
				if (tramDao.insert(ob) > -1) {
					Toast.makeText(getApplicationContext(),
							R.string.tao_thanh_cong_, Toast.LENGTH_SHORT)
							.show();
				} else {
					Toast.makeText(getApplicationContext(),
							R.string.tao_that_bai_, Toast.LENGTH_SHORT).show();
				}

			} catch (Exception e) {
				Toast.makeText(getApplicationContext(), R.string.tao_that_bai_,
						Toast.LENGTH_SHORT).show();
			}
		} else {
			try {
				ob.setId_object(object.getId_object());
				tramDao.update(ob);
				Toast.makeText(getApplicationContext(),
						R.string.chinh_sua_thanh_cong_, Toast.LENGTH_SHORT)
						.show();
			} catch (Exception e) {
				Toast.makeText(getApplicationContext(),
						R.string.chinh_sua_khong_thanh_cong_,
						Toast.LENGTH_SHORT).show();
			}
		}

		finish();

	}

	private void dispatchTakePictureIntent(boolean gps, int request) {

		Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

		File filephoto = null;
		try {
			filephoto = setupphotos.createImageFile();

		} catch (IOException e) {
			e.printStackTrace();
			filephoto = null;
			mCurrentPhotoPath = null;
		}
		if (gps) {
			if (!locationTracker.servicesConnected()) {
				Toast.makeText(this,
						R.string.kiem_tra_ket_noi_internet_hoac_bat_gps,
						Toast.LENGTH_SHORT).show();
				return;
			}
		}
		if (filephoto != null) {
			takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,
					Uri.fromFile(filephoto));
			mCurrentPhotoPath = filephoto.getAbsolutePath();
			startActivityForResult(takePictureIntent, request);

		}

	}

}
